using CommandLine.Text;
using FileSubscriptionServer.Helpers;
using FileSubscriptionServer.Models;
using Newtonsoft.Json;
using System.Text.Json.Serialization;

namespace FileSubscriptionServer
{
    public class Program
    {
        public static void Main(string[] args)
        {
            var argsResult = CommandLine.Parser.Default.ParseArguments<UserInput>(args);
            if (argsResult.Errors?.Any() == true)
                return;

            if (argsResult.Value.Check() != true)
            {
                return;
            }

            if (string.IsNullOrEmpty(argsResult.Value.WatchConfig) != true && File.Exists(argsResult.Value.WatchConfig))
            {
                var config = JsonConvert.DeserializeObject<WatchConfig>(File.ReadAllText(argsResult.Value.WatchConfig));
                if (config?.Watchs != null)
                {
                    foreach (var watchItem in config.Watchs)
                    {
                        FileManager.AddWatch(watchItem.Watch, watchItem.Id);
                    }
                }
            }
            else
            {
                foreach (var item in argsResult.Value.WatchPaths)
                {
                    FileManager.AddWatch(item);
                }
            }

            var builder = WebApplication.CreateBuilder(args);

            // Add services to the container.

            builder.Services.AddControllers();

            var app = builder.Build();

            // Configure the HTTP request pipeline.

            app.UseAuthorization();


            app.MapControllers();

            app.Run();
        }
    }
}
